package com.wwm.findit;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.Holder;
import com.orhanobut.dialogplus.ListHolder;
import com.orhanobut.dialogplus.OnCancelListener;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class MainActivity extends Activity implements AMapLocationListener, LocationSource, AMap.OnMarkerClickListener,
        AMap.OnInfoWindowClickListener, InfoWindowAdapter {

    final static String TAG = "FindIt";

    private MapView mapView;
    private AMap aMap;

    private LocationManagerProxy mLocationManagerProxy;
    private OnLocationChangedListener mListener;

	private RequestQueue mRequestQueue;

	ArrayList<Marker> markerArray;
	ArrayList<Item> itemArray;
	SimpleAdapter mSimpleAdapter;

	boolean isZoomed;

    Double curLat;
    Double curLng;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 必须要写
        init();
        Button btn_account = (Button) findViewById(R.id.button_account);
        btn_account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("android.intent.action.AccountActivity");
                startActivity(intent);
            }
        });
        Button btn_get = (Button) findViewById(R.id.button_get);
        btn_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // Toast.makeText(MainActivity.this, "hahaha", Toast.LENGTH_SHORT).show();
                showListDialog(0, DialogPlus.Gravity.BOTTOM, false, false);
            }
        });

		mRequestQueue = Volley.newRequestQueue(this);
		itemArray = new ArrayList<Item>();
		markerArray = new ArrayList<Marker>();
		isZoomed = false;
		mSimpleAdapter = new SimpleAdapter(MainActivity.this);
    }


    private void setUpMap() {

        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式

        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setCompassEnabled(true);

        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式：定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）
        // 地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）三种模式
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }

    /**
     * 初始化定位
     */
    private void initLocation() {
        mLocationManagerProxy = LocationManagerProxy.getInstance(this);
        //此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        //注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
        //在定位结束后，在合适的生命周期调用destroy()方法
        //其中如果间隔时间为-1，则定位只定一次
        mLocationManagerProxy.requestLocationData(
                LocationProviderProxy.AMapNetwork, 5 * 1000, 15, this);
        mLocationManagerProxy.setGpsEnable(false);
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        setUpMap();

        //initLocation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        //mLocationManagerProxy.destroy();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        deactivate();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLocationChanged(final AMapLocation aMapLocation) {
        // 通过 AMapLocation.getAMapLocException()方法获取定位异常对象，再通过异常对象返回的错误码判断是或否定位成功。
        if (aMapLocation != null && aMapLocation.getAMapException().getErrorCode() == 0) {
            //获取位置信息
            curLat = aMapLocation.getLatitude();
            curLng = aMapLocation.getLongitude();
			GlobalData.currentLat = curLat;
			GlobalData.currentLng = curLng;

            Log.d(TAG, "Latitude = " + curLat.doubleValue() + ", Longitude = " + curLng.doubleValue());

            // 通过 AMapLocation.getExtras() 方法获取位置的描述信息，包括省、市、区以及街道信息，并以空格分隔。
            String desc = "";
            Bundle locBundle = aMapLocation.getExtras();
            if (locBundle != null) {
                desc = locBundle.getString("desc");
                Log.d(TAG, "desc = " + desc);
            }


			Map<String, String> map = new HashMap<String, String>();
			//Lng, Lat, d, istance
			map.put("Lat", Double.toString(curLat));
			map.put("Lng", Double.toString(curLng));
			map.put("distance", "5000");
			Log.i("FindIt", map.toString());

			JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.GET_MAP_ITEM_URL, new JSONObject(map), new Response.Listener<JSONObject>()
			{
				@Override
				public void onResponse(JSONObject response)
				{
					Log.i("FindIt", response.toString());

						for (int i = 0 ; i < markerArray.size() ; i++)
						{
							markerArray.get(i).remove();
						}
						markerArray.clear();

						int count = 0;
						itemArray.clear();
						try
						{
							Iterator it = response.keys();
							while (it.hasNext())
							{
								String key = (String) it.next();
                                if (key.equals("success"))
                                    continue;
								JSONObject j = response.getJSONObject(key);
								Item p = new Item(j);
								itemArray.add(p);

								MarkerOptions markerOptions = new MarkerOptions();
								// 设置Marker的坐标，为我们点击地图的经纬度坐标
								markerOptions.position(new LatLng(Float.parseFloat(p.latitude), Float.parseFloat(p.longtitude)));
								// 设置Marker的可见性
								markerOptions.title(Integer.toString(count));
								markerOptions.visible(true);
								markerOptions.draggable(false);
								markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.chest_close));
								// 将Marker添加到地图上去
								markerArray.add(aMap.addMarker(markerOptions));
                                count++;
								//petIDArray.add(Integer.parseInt(value));
							}
						} catch (JSONException e)
						{
							e.printStackTrace();
						}
				}
			}, new Response.ErrorListener()
			{
				@Override
				public void onErrorResponse(VolleyError error)
				{
					Log.i("FindIt", error.getMessage());
				}
			});
			mRequestQueue.add(jr);

			if (isZoomed == false)
			{
				aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(curLat, curLng), 30));
				isZoomed = true;
			}
            mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
        }
    }


    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mLocationManagerProxy == null) {
            mLocationManagerProxy = LocationManagerProxy.getInstance(this);
            //此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            //注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
            //在定位结束后，在合适的生命周期调用destroy()方法
            //其中如果间隔时间为-1，则定位只定一次
            mLocationManagerProxy.requestLocationData(
                    LocationProviderProxy.AMapNetwork, 5 * 1000, 5, this);
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationManagerProxy != null) {
            mLocationManagerProxy.removeUpdates(this);
            mLocationManagerProxy.destroy();
        }
        mLocationManagerProxy = null;
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        boolean status = marker.isInfoWindowShown();
        if (status == true) {
            marker.hideInfoWindow();
        } else {
            marker.showInfoWindow();
        }

        return true;
    }

    public void scanQRcode(View view) {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        integrator.initiateScan();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                //Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
				String md5 = result.getContents();
				String username = GlobalData.username;

				Map<String, String> map = new HashMap<String, String>();
				map.put("md5", md5);
				map.put("username", username);
				Log.i("FindIt", map.toString());

				/*
				*  $Lng = (float)$obj->{'Lng'};
		$Lat = (float)$obj->{'Lat'};
		$md5 = $obj->{'md5'};
		$username = $obj->{'username'};
				* */

				JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.RECEIVE_ITEM_URL, new JSONObject(map), new Response.Listener<JSONObject>()
				{
					@Override
					public void onResponse(JSONObject response)
					{
						Log.i("FindIt", response.toString());
						try
						{
							int retCode = response.getInt("success");
							if (retCode == 0)
							{
								Toast.makeText(MainActivity.this, response.getString("message"), Toast.LENGTH_SHORT).show();
							}
							else
							{
								Toast.makeText(MainActivity.this, response.getString("message"), Toast.LENGTH_SHORT).show();
								return ;
							}
						} catch (JSONException e)
						{
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener()
				{
					@Override
					public void onErrorResponse(VolleyError error)
					{
						Log.i("FindIt", error.getMessage());
					}
				});
				mRequestQueue.add(jr);

            }
        } else {
            // This is important, otherwise the result will not be passed to the fragment
            super.onActivityResult(requestCode, resultCode, data);
        }
    }


    @Override
    public void onInfoWindowClick(Marker marker) {
        //Toast.makeText(MainActivity.this, "hahaha", Toast.LENGTH_SHORT).show();
		String titleString = marker.getTitle();
		int index = Integer.parseInt(titleString);
		Item item = itemArray.get(index);

		if (GlobalData.userLevel < item.level)
		{
			Toast toast = Toast.makeText(this, "您的等级太低，不能打开此宝箱", Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 50);
			toast.show();
			return ;
		}

        showDialog(0, DialogPlus.Gravity.BOTTOM, false, false,item);
    }

    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = getLayoutInflater().inflate(R.layout.simple_info_window, null);

        TextView itemName = (TextView) infoWindow.findViewById(R.id.marker_info_item_name);
        TextView itemDistance = (TextView) infoWindow.findViewById(R.id.marker_info_distance);

        String titleString = marker.getTitle();
		int index = Integer.parseInt(titleString);
		Item item = itemArray.get(index);

        final double latitude = marker.getPosition().latitude;
        final double longitude = marker.getPosition().longitude;

        Float distance = AMapUtils.calculateLineDistance(new LatLng(curLat, curLng), new LatLng(latitude, longitude));

        itemName.setText("物品:" + item.itemname + " 等级:" + item.level + " 价值:" + item.value);
        itemDistance.setText("距离您约" + ((int)distance.floatValue()) + "米");

        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    private void showListDialog(int holderId, DialogPlus.Gravity gravity, boolean showHeader, boolean showFooter) {
        ListHolder holder;

        holder = new ListHolder();

        OnClickListener clickListener = new OnClickListener() {
            @Override
            public void onClick(DialogPlus dialog, View view) {
                switch (view.getId()) {
                }
                dialog.dismiss();
            }
        };

        OnDismissListener dismissListener = new OnDismissListener() {
            @Override
            public void onDismiss(DialogPlus dialog) {

            }
        };

        OnCancelListener cancelListener = new OnCancelListener() {
            @Override
            public void onCancel(DialogPlus dialog) {

            }
        };

		Map<String, String> map = new HashMap<String, String>();
		map.put("username", GlobalData.username);

		JsonObjectRequest jr = new JsonObjectRequest(Request.Method.POST, GlobalData.GET_USER_ITEM_URL, new JSONObject(map), new Response.Listener<JSONObject>()
		{
			@Override
			public void onResponse(JSONObject response)
			{
				Log.i("FindIt", response.toString());

					ArrayList<Item> itemArray = new ArrayList<Item>();
					try {
						Iterator it = response.keys();
						while (it.hasNext()) {
							String key = (String) it.next();
							JSONObject j = response.getJSONObject(key);
							Item p = new Item(j);
							itemArray.add(p);
						}

						mSimpleAdapter.setData(itemArray);
						mSimpleAdapter.notifyDataSetChanged();
					} catch (JSONException e) {
						e.printStackTrace();
					}
			}
		}, new Response.ErrorListener()
		{
			@Override
			public void onErrorResponse(VolleyError error)
			{
				Log.i("FindIt", error.getMessage());
			}
		});
		mRequestQueue.add(jr);


        final DialogPlus dialog = new DialogPlus.Builder(this)
                .setBackgroundColorResourceId(R.color.transparent_full)
                .setContentHolder(holder)
                .setCancelable(true)
                .setGravity(gravity)
                .setAdapter(mSimpleAdapter)
                .setOnClickListener(clickListener)
                .setOnDismissListener(dismissListener)
                .setOnCancelListener(cancelListener)
                .create();

        ListView view = (ListView)dialog.getHolderView();
        view.setSelector(R.drawable.itemselected);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) view.getLayoutParams();
        lp.height = 660;
        view.setLayoutParams(lp);
        dialog.show();
    }

    private void showDialog(int holderId, DialogPlus.Gravity gravity, boolean showHeader, boolean showFooter,Item item) {
        Holder holder;

        holder = new ViewHolder(R.layout.detail_info_dialog);


        OnClickListener clickListener = new OnClickListener() {
            @Override
            public void onClick(DialogPlus dialog, View view) {
                switch (view.getId()) {
                }
                dialog.dismiss();
            }
        };

        OnDismissListener dismissListener = new OnDismissListener() {
            @Override
            public void onDismiss(DialogPlus dialog) {

            }
        };

        OnCancelListener cancelListener = new OnCancelListener() {
            @Override
            public void onCancel(DialogPlus dialog) {

            }
        };


        final DialogPlus dialog = new DialogPlus.Builder(this)
                .setContentHolder(holder)
                .setCancelable(true)
                .setGravity(gravity)
                .setOnClickListener(clickListener)
                .setOnDismissListener(dismissListener)
                .setOnCancelListener(cancelListener)
                .create();

        TextView tips_1 = (TextView) dialog.getHolderView().findViewById(R.id.tips_1);
        TextView tips_2 = (TextView) dialog.getHolderView().findViewById(R.id.tips_2);
        TextView tips_3 = (TextView) dialog.getHolderView().findViewById(R.id.tips_3);
        TextView note = (TextView) dialog.getHolderView().findViewById(R.id.note);
        tips_1.setText("线索1:"+item.tip1);
        tips_2.setText("线索2:"+item.tip2);
        tips_3.setText("线索3:"+item.tip3);
        note.setText("留言:"+item.msg);
        dialog.show();
    }

}
